<template>
  <van-nav-bar
    title="购物车"
    left-text="返回"
    left-arrow
    right-text="清空"
    @click-left="router.back()"
  />
  <van-checkbox-group v-model="checked">
    <van-swipe-cell v-for="(item, index) in data.cartList" :key="item.id">
      <!-- 滑块的左边 -->
      <div
        style="
          margin: 10px;
          padding: 10px;
          display: flex;
          border-radius: 10px;
          background-color: white;
        "
      >
        <div
          style="
            width: 10%;
            display: flex;
            justify-content: center;
            align-items: center;
          "
        >
          <van-checkbox :name="item.id" @click="checkOne"></van-checkbox>
        </div>
        <!-- 图片 -->
        <div style="width: 30%">
          <img :src="item.pic" style="width: 100%" />
        </div>
        <div
          style="
            width: 60%;
            display: flex;
            flex-direction: column;
            justify-content: space-around;
            margin-left: 10px;
          "
        >
          <!-- 商品名称 -->
          <div style="font-size: 0.9em">{{ item.name }}</div>
          <div style="display: flex; justify-content: space-between">
            <!-- 价格 -->
            <span style="font-size: 1.2em; color: red">¥{{ item.price }}</span>
            <!-- 数量 -->
            <van-stepper
              v-model="item.buyCount"
              theme="round"
              button-size="22"
              disable-input
            />
          </div>
        </div>
      </div>
      <!-- 滑块右边 -->
      <template #right>
        <van-button
          square
          text="删除"
          type="danger"
          class="delete-button"
          @click="del(item, index)"
        />
      </template>
    </van-swipe-cell>
  </van-checkbox-group>
  <!-- 提交订单栏 -->
  <van-submit-bar :price="total" button-text="提交订单" @submit="onSubmit">
    <van-checkbox v-model="allStatus" @change="checkAll">全选</van-checkbox>
    <template #tip>
      你的收货地址不支持配送, <span @click="onClickLink">修改地址</span>
    </template>
  </van-submit-bar>
</template>

<script setup lang="ts">
import { reactive, ref, computed } from "vue";
import { useRouter } from "vue-router";
import req from "@/utils/req";
import { showToast } from "vant";
import { useCartStore } from '@/stores/cart'

const storeCart = useCartStore()

const router = useRouter();
interface Data {
  cartList: any;
}
const data: Data = reactive({
  cartList: [],
});
req.get("http://localhost:3000/cartList").then((res) => {
  console.log(res);
  data.cartList = res.data;
});
//删除
const del = (item: { id: string }, index: number) => {
  req.delete("http://localhost:3000/cartList/" + item.id).then((res) => {
    if (res) {
      showToast({
        message: "删除商品成功",
        duration: 700,
        icon: "close",
        onClose: () => {
          data.cartList.splice(index, 1);
        },
      });
      storeCart.cartList.splice(index,1)
    }
  });
};
//清空

//服务端问题，暂时实现不了清空，
// 添加 @click-right="clear"在van-nav-bar后调用方法
// const clear = () => {
//   data.cartList.forEach((item:any) => {
//     setTimeout(() => {
//       req.delete('http://localhost:3000/cartList'+ item.id).then((res) => {
//         // 重新加载当前页面
//         window.location.reload()
//       })
//     }, 1000)
//   })
// }

// 选择的商品的列表  id
const checked: any = ref([]);
// 选择计算总价

const total = computed(() => {
  // 选中的商品的id
  let total_price = 0;
  //ref需要加.value
  checked.value.forEach((item: any) => {
    data.cartList.forEach((item1: any) => {
      if (item === item1.id) {
        total_price += item1.buyCount * item1.price;
      }
    });
  });
  console.log(total_price);
  //单位是分，所以需要转为元
  return total_price * 100;
});

//下单
const onSubmit = () => {
    if (!localStorage.getItem('token')) {
    showToast({
      message: '请先登录',
      duration: 1000,
      onClose: () => {
        // 登录后回调的页面
        router.push('/login?goto=/cart')
      }
    })
  } else {
    // 选中商品为0  不下单
    if (checked.value.length === 0) {
      showToast('细狗买点儿东西吧~')

      return false
    }
    showToast('下单维护中')
  }
};

//修改地址
const onClickLink = () => {
  router.push("/address");
};

//全选的状态
const allStatus = ref(false)
checkAll()
function checkAll(){
    if(allStatus.value === true){
        //map()遍历数组，返回一个新数组
        checked.value = data.cartList.map(function(item:any){
           return item.id
        })
    }else{
    // 什么时候反选清空数据  买了所有的时候，才可以清空选中列表
       if(data.cartList.length === checked.value.length) {
        checked.value = []
       }
}
}
const checkOne = () => {
    //=== 返回布尔值
    allStatus.value = checked.value.length === data.cartList.length
}

</script>

<style lang="scss" scoped>
.van-button:before {
  border: none;
}
.delete-button {
  height: 100%;
}
</style>
